﻿using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Net;
using System.IO;
using imeem.api;
using imeem.api.util;

namespace ImeemUploadr
{
	public class Users
	{
		public static string usersLoginUri = "http://www.api.imeem.com/api/xml/usersLogin?apiKey={0}&version={1}&sig={2}&username={3}&password={4}&keepLoggedIn={5}";
		private string apiKey = string.Empty;
		private string apiSecret = string.Empty;
		
		public Users(string key, string secret)
		{
			this.apiKey = key;
			this.apiSecret = secret;
		}
		
		public static string GenerateUsersLoginUri(string apiKey, string version, string sig, string username, string password, string keepLoggedIn)
		{
			return string.Format(usersLoginUri, apiKey, version, sig, username, password, keepLoggedIn);
		}
		
		public CookieCollection LoginUser(string username, string password, bool keepLoggedIn)
		{
			string keepLoggedInString = keepLoggedIn.ToString().ToLower();
			Hashtable parameters = new Hashtable();
			parameters.Add("apiKey", this.apiKey);
			parameters.Add("version", "1.0");
			parameters.Add("username", username);
			parameters.Add("password", password);
			parameters.Add("keepLoggedIn", keepLoggedInString);
			string sig = Util.GenerateSignature("usersLogin", parameters, apiSecret);
			parameters.Add("sig", sig);
			
			string uri = GenerateUsersLoginUri(
				parameters["apiKey"] as string, 
				parameters["version"] as string, 
				parameters["sig"] as string, 
				parameters["username"] as string,
				parameters["password"] as string,
				parameters["keepLoggedIn"] as string
			);
			
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
			request.Timeout = 10000;
			request.CookieContainer = new CookieContainer();
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			Encoding encoding = Encoding.GetEncoding(1252);
			StreamReader responseStream = new StreamReader(response.GetResponseStream());
			string data = responseStream.ReadToEnd();
			response.Close();
			responseStream.Close();
			return response.Cookies;
		}
	}
}
